package com.aiyun.securiy.login.security;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		Map<String, Object> data = jdbcTemplate.queryForMap("select login, password, roles from sys_user where login=?", s);

		if (data.isEmpty()) {
			throw new UsernameNotFoundException("用户不存在");
		}

		String[] roles = data.get("roles").toString().split(",");
		List<String> roleList = Arrays.asList(roles);
		return new User(
				s,
				data.get("password").toString(),
				roleList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())
		);
	}
}
